package com.chungkui.bond.oauth2.server.service.impl;

import com.chungkui.bond.authmanager.bean.UserInfo;
import com.chungkui.bond.common.core.bean.SecurityUser;
import com.chungkui.bond.oauth2.server.service.UserInfoService;
import com.chungkui.bond.oauth2.server.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author zhs
 */
@Service("iUserDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserInfoService userInfoService;
    @Autowired
    UserRoleService userRoleService;

    /**
     * 获取并封装用户信息
     * 只取用户认证基本信息和用户角色信息其余信息不获取
     * 房子客户端查询权限相关信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userInfoService.getByUsername(username);
        Set<GrantedAuthority> roles = userRoleService.listRoleCodesByUserInfo(userInfo);
        SecurityUser securityUser =new SecurityUser(username,userInfo.getPassword(),roles);
        securityUser.setId(userInfo.getId());
        return securityUser;
    }
}
